package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.NcOutputMilkMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.INcOrderCfService;
import com.ruoyi.system.service.INcOrderService;
import com.ruoyi.system.service.INcOutputMilkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 牛奶出库 服务层实现
 *
 * @author ruoyi
 * @date 2019-09-11
 */
@Service
public class NcOutputMilkServiceImpl implements INcOutputMilkService
{
	@Autowired
	private NcOutputMilkMapper ncOutputMilkMapper;

	@Autowired
	private INcOrderService orderService;

	@Autowired
	private SysDictDataMapper dictDataMapper;

	@Autowired
	private INcOrderCfService orderCfService;

	/**
     * 查询牛奶出库信息
     *
     * @param outputId 牛奶出库ID
     * @return 牛奶出库信息
     */
    @Override
	public NcOutputMilk selectNcOutputMilkById(Long outputId)
	{
	    return ncOutputMilkMapper.selectNcOutputMilkById(outputId);
	}

	/**
     * 查询牛奶出库列表
     *
     * @param ncOutputMilk 牛奶出库信息
     * @return 牛奶出库集合
     */
	@Override
	public List<NcOutputMilk> selectNcOutputMilkList(NcOutputMilk ncOutputMilk)
	{
	    return ncOutputMilkMapper.selectNcOutputMilkList(ncOutputMilk);
	}

    /**
     * 新增牛奶出库
     *
     * @param ncOutputMilk 牛奶出库信息
     * @return 结果
     */
	@Override
	public int insertNcOutputMilk(NcOutputMilk ncOutputMilk)
	{
	    return ncOutputMilkMapper.insertNcOutputMilk(ncOutputMilk);
	}

	/**
     * 修改牛奶出库
     *
     * @param ncOutputMilk 牛奶出库信息
     * @return 结果
     */
	@Override
	public int updateNcOutputMilk(NcOutputMilk ncOutputMilk)
	{
	    return ncOutputMilkMapper.updateNcOutputMilk(ncOutputMilk);
	}

	/**
     * 删除牛奶出库对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteNcOutputMilkByIds(String ids)
	{
		return ncOutputMilkMapper.deleteNcOutputMilkByIds(Convert.toStrArray(ids));
	}

	@Override
	public int createOrderByIds(String ids, SysUser user) {
		NcOrder o = new NcOrder();
		if (StringUtils.isNotEmpty(ids)){
			String orderCode= DateUtils.parseDateToStr("yyyyMMddHHmmss", new Date())+"xxx";
			o.setOrderCode(orderCode);
			o.setOrderType(Constants.ORDER_MILK_OUTPUT);
			o.setOrderTime(new Date());
			o.setCreateTime(new Date());
			o.setCreateBy(user.getUserName());
			orderService.insertNcOrder(o);

			String[] idArr = Convert.toStrArray(ids);
			for (String id : idArr){
				NcOutputMilk ncOutputMilk = ncOutputMilkMapper.selectNcOutputMilkById(Long.parseLong(id));
				ncOutputMilk.setOrderId(o.getOrderId());
				ncOutputMilk.setOutputType(3);
				updateNcOutputMilk(ncOutputMilk);
			}
			return 1;
		}else{
			return 0;
		}

	}

	@Override
	public void SelectNcOutMilkTotal(ModelMap mmap, NcOutputMilk ncOutputMilk) {
		// 查出所有的内销类型
		List<SysDictData> typeList = dictDataMapper.selectDictDataByType("outputType");
		List<String> keysList = new ArrayList<>();
		for(SysDictData data: typeList){
			keysList.add(data.getDictLabel());
		}
		String startTime = (String) ncOutputMilk.getParams().get("beginTime");
		String endTime = (String) ncOutputMilk.getParams().get("endTime");
		List<BigDecimal> valList = new ArrayList<>(typeList.size());
		BigDecimal totalAll = new BigDecimal("0");
		List<NcOutputMilk> totalList = new ArrayList<>();
		for(int i = 0 ; i < typeList.size(); i++){
			totalList = ncOutputMilkMapper.selectMilkTotalByOutPutType(Integer.parseInt(typeList.get(i).getDictValue()),startTime,endTime);
			BigDecimal total = totalList.stream().filter(t->StringUtils.isNotNull(t.getOutputAmout())).map(NcOutputMilk::getOutputAmout).reduce(BigDecimal.ZERO,BigDecimal::add);
			valList.add(total);
		}
		totalAll = valList.stream().reduce(BigDecimal.ZERO,BigDecimal::add);
		keysList.add(0,"总产奶量");
		List<Map> list = new ArrayList<>();
		for(int i = 0 ; i < keysList.size(); i++){
			Map<String,String> map  = new HashMap<>();
			map.put("key",keysList.get(i));
			map.put("val",i == 0 ?totalAll.intValue()+"":valList.get(i-1).toString());
			map.put("class",i == 0 ? (i+1)+"  active" : String.valueOf(i+1));
			map.put("type",i == 0 ? "no" :typeList.get(i-1).getDictValue());
			list.add(map);
		}
		//  求每个月的牛奶产量
		String[] last12Months = new String[12];
		Calendar cal = Calendar.getInstance();
		List sum=new ArrayList<>();
		if (StringUtils.isNotEmpty(endTime)) {
			cal.setTime(DateUtils.dateTime("yyyy-MM-dd",endTime));
			//如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
			cal.set(Calendar.DAY_OF_MONTH, 1);
			for (int i = 0; i < 12; i++) {
				if(cal.get(Calendar.MONTH)+1<10){
					last12Months[11 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1);
				}else{
					last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
				}
				cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月

			}
		}
		else if(StringUtils.isNotEmpty(startTime)){
			cal.setTime(DateUtils.dateTime("yyyy-MM-dd",startTime));
			//如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
			cal.set(Calendar.DAY_OF_MONTH, 1);
			for (int i = 0; i < 12; i++) {
				if(cal.get(Calendar.MONTH)+1<10){
					last12Months[11 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1);
				}else{
					last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
				}
				cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月

			}
		}
		else{
			//如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
			cal.set(Calendar.DAY_OF_MONTH, 1);
			for (int i = 0; i < 12; i++) {
				if(cal.get(Calendar.MONTH)+1<10){
					last12Months[11 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1);
				}else{
					last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
				}
				cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月

			}
		}
		for(int i = 0; i < last12Months.length; i++){
			Double d = ncOutputMilkMapper.selectMilkTotalByMonth(last12Months[i], null);
			sum.add(StringUtils.isNotNull(d) ? d : 0);
		}
		mmap.put("sum",sum);
		mmap.put("list",list);
		mmap.put("xDate",last12Months);
	}

	@Override
	public void selectNcOutputMilkOrderInfoByOrderId(String orderId, ModelMap mmap) {
	}

	@Override
	public List<NcOutputMilk> selectNcoutputMilkOrderInfoByOrderId(Long orderId) {
		return ncOutputMilkMapper.selectMilkOrderInfoByOrderId(orderId);
	}

	@Override
	public void innoInfo(String beginTime, String endTime, ModelMap mmap, String dataType, String output) {
		// 查出所有的内销类型
		List<SysDictData> typeList = dictDataMapper.selectDictDataByType("outputType");
		List<Map> outPutTypeList = new ArrayList<>();
		Map first = new HashMap();
		first.put("val","总计");
		first.put("type","all");
		if(StringUtils.isBlank(output)){   // 总计类型
			first.put("class"," item active");
			for(SysDictData data : typeList){
				Map<String,String> map = new HashMap<>();
				map.put("val",data.getDictLabel());
				map.put("type",data.getDictValue());
				map.put("class"," item");
				outPutTypeList.add(map);
			}
		}else{   // 非总计类型
			first.put("class"," item ");
			for(SysDictData data : typeList){
				Map<String,String> map = new HashMap<>();
				if(output.equals(data.getDictValue())){
					map.put("class"," item active");
				}else{
					map.put("class"," item");
				}
				map.put("val",data.getDictLabel());
				map.put("type",data.getDictValue());
				outPutTypeList.add(map);
			}
		}
		outPutTypeList.add(0,first);
		Map milkMap = new HashMap();
		milkMap.put("name","牛奶总产量");
		Double amount = ncOutputMilkMapper.selectMilkTotalByMonthRange(beginTime,endTime,output);
		milkMap.put("amount",amount == null ? 0 : amount);
		// 趋势和日均
		int totalDays = findDays(dataType);
		if("year".equals(dataType)){  // 年趋势
		List<String> monthList = DateUtils.getEachMonthList();
		List<Double> totalList = new ArrayList<>();
		for(String s : monthList){
			Double total = ncOutputMilkMapper.selectMilkTotalByMonth(s,output);
			totalList.add(total == null ? 0 : total);
		}
		mmap.put("xDate",monthList);
		mmap.put("yDateMilk",totalList);
		}else if("month".equals(dataType)){  // 月趋势
			List<String> daysList = DateUtils.getEachDaysList();
			List<Double> totalList = new ArrayList<>();
			for(String s : daysList){
				Double total = ncOutputMilkMapper.selectMilkTotalByDays(s,output);
				totalList.add(total == null ? 0 : total);
			}
			mmap.put("xDate",daysList);
			mmap.put("yDateMilk",totalList);

		}else if("day".equals(dataType)){   // 日趋势
			List<String> daysList = DateUtils.getBeforeSevenDay();
			List<Double> totalList = new ArrayList<>();
			for(String s : daysList){
				Double total = ncOutputMilkMapper.selectMilkTotalByDays(s,output);
				totalList.add(total == null ? 0 : total);
			}
			mmap.put("xDate",daysList);
			mmap.put("yDateMilk",totalList);
		}else if("search".equals(dataType)){   // 时间段查询
			List<String> daysList = DateUtils.getBetweenTime(beginTime,endTime);
			totalDays = daysList.size();
			List<Double> totalList = new ArrayList<>();
			for(String s : daysList){
				Double total = ncOutputMilkMapper.selectMilkTotalByDays(s, output);
				totalList.add(total == null ? 0 : total);
			}
			mmap.put("xDate",daysList);
			mmap.put("yDateMilk",totalList);
		}else{
		}
		milkMap.put("dayAmount",amount == null ? 0 : division(amount,totalDays));
		mmap.put("milk",milkMap);
		mmap.put("list",outPutTypeList);
	}
	private Object division(Double a, int b) {
		String result = "";
		double num =(double)a/b;
		DecimalFormat df = new DecimalFormat("0.0");
		result = df.format(num);
		return result;
	}

	private int findDays(String dataType) {
		Date yearsDate = DateUtils.getBeginDayOfYear();
		Date monthDate = DateUtils.getBeginDayOfMonth();
		Date nowDate = DateUtils.getNowDate();
		if("year".equals(dataType)){
			return DateUtils.getDiffDays(yearsDate,nowDate);
		}else if("month".equals(dataType)){
			return DateUtils.getDiffDays(monthDate,nowDate);
		}else{
			return 1;
		}
	}

	@Override
	public void innoInfoType(String beginTime, String endTime, ModelMap mmap, String type) {
		// 查出所有的内销类型
		List<SysDictData> typeList = dictDataMapper.selectDictDataByType("outputType");
		List<Map> outPutTypeList = new ArrayList<>();

		for(SysDictData data : typeList){
			Map<String,String> map = new HashMap<>();
			map.put("val",data.getDictLabel());
			map.put("type",data.getDictValue());
			map.put("class"," item");
			outPutTypeList.add(map);
		}
		Map first = new HashMap();
		first.put("val","总计");
		first.put("type","all");
		first.put("class"," item active");
		outPutTypeList.add(0,first);
		Map milkMap = new HashMap();
		milkMap.put("name","牛奶总产量");
		Double amount = ncOutputMilkMapper.selectMilkTotalByMonthRange(beginTime,endTime, null);
		milkMap.put("amount",amount == null ? 0 : amount);
		mmap.put("milk",milkMap);
		mmap.put("list",outPutTypeList);
	}




	@Override
	public List<Map> selectCountByTime(Integer spanType, String beginTime, String endTime ,Integer cforderType) {
		Date s = null;
		Date e = null;
		Map se = orderCfService.calTimeSpan(s, e, beginTime, endTime, spanType);
		s = (Date) se.get("s");
		e = (Date) se.get("e");

		return getSumByDate(spanType, s, e,cforderType);
	}

	@Override
	public List<NcOutputMilk> selectNcoutputMilkOrderInfoByOutputType(Integer outputType) {
		return ncOutputMilkMapper.selectMilkOrderInfoByOutputType(outputType);
	}

	@Override
	public double selectNcCowsMilkScreen(NcOutputMilk ncOutputMilk) {
		return ncOutputMilkMapper.selectNcCowsMilkScreen(ncOutputMilk);
	}
	//前端内部消息
	@Override
	public List<Map> selectInfoByTime(Integer spanType, String beginTime, String endTime,String outputType) {
		Date s = null;
		Date e = null;
		Map se = orderCfService.calTimeSpan(s, e, beginTime, endTime, spanType);
		s = (Date) se.get("s");
		e = (Date) se.get("e");

		return getSumInfoByDate(spanType, s, e,outputType);
	}
	//前端内部消息
	private List<Map> getSumInfoByDate(Integer spanType, Date s, Date e,String outputType) {
		List<Map> result = new ArrayList<>();
		if (spanType == 1) {
			while (e.getTime() >= s.getTime()) {
				String dateSpan = DateUtils.parseDateToStr("yyyy", s);

				Map m = new HashMap();
				m.put("x", dateSpan);
				m.put("milkCount", getByDate(dateSpan, spanType,outputType));
				result.add(m);

				s = DateUtils.addYears(s, 1);
			}
		} else if (spanType == 2) {
			while (e.getTime() >= s.getTime()) {
				String dateSpan = DateUtils.parseDateToStr("yyyy-MM", s);
				Map m = new HashMap();
				m.put("x", dateSpan);
				m.put("milkCount", getByDate(dateSpan, spanType,outputType));
				result.add(m);
				s = DateUtils.addMonths(s, 1);
			}
		} else if (spanType == 3) {
			while (e.getTime() >= s.getTime()) {
				String dateSpan = DateUtils.parseDateToStr("yyyy-MM-dd", s);
				Map m = new HashMap();
				m.put("x", dateSpan);
				m.put("milkCount", getByDate(dateSpan, spanType,outputType));
				result.add(m);
				s = DateUtils.addDays(s, 1);
			}
		}
		return result;
	}
	//前端内部消息
	private Double getByDate(String dateSpan, Integer dataSpan,String outputType) {
		NcOutputMilk milk = new NcOutputMilk();
		if (dataSpan == null || dataSpan == 2) {
			milk.getParams().put("dateSpanMonth", dateSpan);
		} else if (dataSpan == 1) {
			milk.getParams().put("dateSpanYear", dateSpan);
		} else if (dataSpan == 3) {
			milk.getParams().put("dateSpanDay", dateSpan);
		}
		if(outputType != null &&  outputType.equals("all") == false){
			milk.setOutputType(Integer.valueOf(outputType));
		}
		return ncOutputMilkMapper.selectMilkInfoByDays(milk);
	}

	private List<Map> getSumByDate(Integer spanType, Date s, Date e,Integer cforderType) {
		List<Map> result = new ArrayList<>();
		if (spanType == 1) {
			while (e.getTime() >= s.getTime()) {
				String dateSpan = DateUtils.parseDateToStr("yyyy", s);

				Map m = new HashMap();
				m.put("x", dateSpan);
				m.put("count", getSumByDate(dateSpan, spanType,cforderType));
				result.add(m);

				s = DateUtils.addYears(s, 1);
			}
		} else if (spanType == 2) {
			while (e.getTime() >= s.getTime()) {
				String dateSpan = DateUtils.parseDateToStr("yyyy-MM", s);
				Map m = new HashMap();
				m.put("x", dateSpan);
				m.put("count", getSumByDate(dateSpan, spanType,cforderType));
				result.add(m);
				s = DateUtils.addMonths(s, 1);
			}
		} else if (spanType == 3) {
			while (e.getTime() >= s.getTime()) {
				String dateSpan = DateUtils.parseDateToStr("yyyy-MM-dd", s);
				Map m = new HashMap();
				m.put("x", dateSpan);
				m.put("count", getSumByDate(dateSpan, spanType,cforderType));
				result.add(m);
				s = DateUtils.addDays(s, 1);
			}
		}
		return result;
	}

	private Double getSumByDate(String date, Integer dataSpan ,Integer cforderType) {
//		NcOutputChicken chicken = new NcOutputChicken();
		NcOutputMilk milk = new NcOutputMilk();
		 milk.setCforderType(cforderType);    //设置cforderType值
		if (dataSpan == null || dataSpan == 2) {
			milk.getParams().put("dateSpanMonth", date);
		} else if (dataSpan == 1) {
			milk.getParams().put("dateSpanYear", date);
		} else if (dataSpan == 3) {
			milk.getParams().put("dateSpanDay", date);
		}
		return ncOutputMilkMapper.selectNcOutputMonthAmount(milk);
	}




}
